package com.enqualcomm.kids.activities;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.enqualcomm.kids.R;
import com.enqualcomm.kids.base.BaseActivity;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.config.userdefault.UserTerminalDefault;
import com.enqualcomm.kids.mvp.NetworkModel;
import com.enqualcomm.kids.network.NetworkListener;
import com.enqualcomm.kids.network.SocketRequest;
import com.enqualcomm.kids.network.socket.request.BasicParams;
import com.enqualcomm.kids.network.socket.request.SaveSilenceParams;
import com.enqualcomm.kids.network.socket.request.UpdateSilenceParams;
import com.enqualcomm.kids.network.socket.response.BasicResult;
import com.enqualcomm.kids.network.socket.response.QuerySilenceResult;
import com.enqualcomm.kids.network.socket.response.QueryUserTerminalInfoResult;
import com.enqualcomm.kids.network.socket.response.TerminallistResult;
import com.enqualcomm.kids.view.AlarmWheelView;
import com.enqualcomm.kids.view.wheelview.NumericWheelAdapter;

import common.utils.DensityUtil;
import common.utils.MyFrontUtil;
import common.utils.PlatformUtil;
import common.utils.PromptUtil;
import common.utils.TimeUtil;

public class SilenceSettingActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    private QuerySilenceResult.Data silenceResult;
    private CheckBox checkbox_allweek;
    private CheckBox checkbox_monday;
    private CheckBox checkbox_tuesday;
    private CheckBox checkbox_wednesday;
    private CheckBox checkbox_thursday;
    private CheckBox checkbox_firday;
    private CheckBox checkbox_saturday;
    private CheckBox checkbox_sunday;
    private AlarmWheelView wheelView_changeHour2;
    private AlarmWheelView wheelView_changeMinute2;
    private AlarmWheelView wheelView_changeHour;
    private AlarmWheelView wheelView_changeMinute;
    private TerminallistResult.Terminal terminal;
    private NetworkModel networkModel;
    private boolean needInit;
    private TextView title_bar_terminal_name_tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_silence_setting);
        terminal = getIntent().getParcelableExtra("terminal");
        silenceResult = getIntent().getParcelableExtra("silenceResult");
        networkModel = new NetworkModel();
        needInit = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (needInit) {
            needInit = false;
            initView();
        }
    }

    private void initView() {
        //初始化标题栏
        findViewById(R.id.title_bar_left_iv).setOnClickListener(this);
        title_bar_terminal_name_tv = (TextView) findViewById(R.id.title_bar_terminal_name_tv);
        //名字，头像
        QueryUserTerminalInfoResult.Data info = new UserTerminalDefault(terminal.userterminalid).getInfo();
        setupTitleIcon(info, terminal.terminalid, terminal.userterminalid, getString(R.string.set_silence));
        MyFrontUtil.initTextViewText(this, title_bar_terminal_name_tv, info.name, getString(R.string.s_add_title_add_begin),
                getString(R.string.s_add_title_add_end), 2, info.name.length() + 2);

        //开始时间结束时间
        {
            int textSize = DensityUtil.adjustFontSize(PlatformUtil.windowWidth(this));
            String[] timeArray1 = silenceResult.begintime.split(":");
            wheelView_changeHour = (AlarmWheelView) findViewById(R.id.wheelView_changeHour);
            wheelView_changeMinute = (AlarmWheelView) findViewById(R.id.wheelView_changeMinute);
            wheelView_changeHour.setAdapter(new NumericWheelAdapter(0, 23));
            wheelView_changeHour.setCyclic(true);
            wheelView_changeHour.setCurrentItem(Integer.parseInt(timeArray1[0]));
            wheelView_changeHour.setLabel(getString(R.string.hour));
            wheelView_changeHour.setTextSizeAndItemCount(textSize, 3);

            wheelView_changeMinute.setAdapter(new NumericWheelAdapter(0, 59));
            wheelView_changeMinute.setCyclic(true);
            wheelView_changeMinute.setLabel(getString(R.string.minute));
            wheelView_changeMinute.setCurrentItem(Integer.parseInt(timeArray1[1]));
            wheelView_changeMinute.setTextSizeAndItemCount(textSize, 3);


            String[] timeArray2 = silenceResult.endtime.split(":");
            wheelView_changeHour2 = (AlarmWheelView) findViewById(R.id.wheelView_changeHour2);
            wheelView_changeMinute2 = (AlarmWheelView) findViewById(R.id.wheelView_changeMinute2);
            wheelView_changeHour2.setAdapter(new NumericWheelAdapter(0, 23));
            wheelView_changeHour2.setCyclic(true);
            wheelView_changeHour2.setCurrentItem(Integer.parseInt(timeArray2[0]));
            wheelView_changeHour2.setLabel(getString(R.string.hour));
            wheelView_changeHour2.setTextSizeAndItemCount(textSize, 3);

            wheelView_changeMinute2.setAdapter(new NumericWheelAdapter(0, 59));
            wheelView_changeMinute2.setCyclic(true);
            wheelView_changeMinute2.setLabel(getString(R.string.minute));
            wheelView_changeMinute2.setCurrentItem(Integer.parseInt(timeArray2[1]));
            wheelView_changeMinute2.setTextSizeAndItemCount(textSize, 3);
        }

        //每周重复
        checkbox_allweek = (CheckBox) findViewById(R.id.checkbox_allweek);
        checkbox_monday = (CheckBox) findViewById(R.id.checkbox_monday);
        checkbox_tuesday = (CheckBox) findViewById(R.id.checkbox_tuesday);
        checkbox_wednesday = (CheckBox) findViewById(R.id.checkbox_wednesday);
        checkbox_thursday = (CheckBox) findViewById(R.id.checkbox_thursday);
        checkbox_firday = (CheckBox) findViewById(R.id.checkbox_firday);
        checkbox_saturday = (CheckBox) findViewById(R.id.checkbox_saturday);
        checkbox_sunday = (CheckBox) findViewById(R.id.checkbox_sunday);

//		if (silenceResult.week>127) {
//			silenceResult.week=127;
//		}
        if (silenceResult.week == 127) {
            checkbox_allweek.setChecked(true);
        }
        char[] weeknum = new char[7];
        String binaryString = Integer.toBinaryString(silenceResult.week);
//		System.out.println("binaryString: "+binaryString);"111110"
        for (int i = 0; i < binaryString.length(); i++) {
            weeknum[i] = binaryString.charAt(binaryString.length() - 1 - i);
        }

        if (weeknum[0] == '1') {
            checkbox_sunday.setChecked(true);
        }
        if (weeknum[1] == '1') {
            checkbox_monday.setChecked(true);
        }
        if (weeknum[2] == '1') {
            checkbox_tuesday.setChecked(true);
        }
        if (weeknum[3] == '1') {
            checkbox_wednesday.setChecked(true);
        }
        if (weeknum[4] == '1') {
            checkbox_thursday.setChecked(true);
        }
        if (weeknum[5] == '1') {
            checkbox_firday.setChecked(true);
        }
        if (weeknum[6] == '1') {
            checkbox_saturday.setChecked(true);
        }

        checkbox_allweek.setOnCheckedChangeListener(this);
        checkbox_monday.setOnCheckedChangeListener(this);
        checkbox_tuesday.setOnCheckedChangeListener(this);
        checkbox_wednesday.setOnCheckedChangeListener(this);
        checkbox_thursday.setOnCheckedChangeListener(this);
        checkbox_firday.setOnCheckedChangeListener(this);
        checkbox_saturday.setOnCheckedChangeListener(this);
        checkbox_sunday.setOnCheckedChangeListener(this);

        //保存按钮
        findViewById(R.id.save_btn).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.save_btn:

                //获取用户设置过后的时间
                int beginHour = wheelView_changeHour.getCurrentItem();
                int beginMinute = wheelView_changeMinute.getCurrentItem();
                int endHour = wheelView_changeHour2.getCurrentItem();
                int endMinute = wheelView_changeMinute2.getCurrentItem();

                if (beginHour > endHour) {
                    PromptUtil.toast(getApplicationContext(), R.string.endtime_later_than_starttime);
                    return;
                } else if (beginHour == endHour && beginMinute >= endMinute) {
                    PromptUtil.toast(getApplicationContext(), R.string.endtime_later_than_starttime);
                    return;
                }


                if (beginHour < 10) {
                    silenceResult.begintime = ("0" + beginHour);
                } else {
                    silenceResult.begintime = ("" + beginHour);
                }
                if (beginMinute < 10) {
                    silenceResult.begintime += (":0" + beginMinute);
                } else {
                    silenceResult.begintime += (":" + beginMinute);
                }

                if (endHour < 10) {
                    silenceResult.endtime = ("0" + endHour);
                } else {
                    silenceResult.endtime = ("" + endHour);
                }
                if (endMinute < 10) {
                    silenceResult.endtime += (":0" + endMinute);
                } else {
                    silenceResult.endtime += (":" + endMinute);
                }

                if (silenceResult.week == 0) {
                    silenceResult.week = TimeUtil.getNextDayOfWeek();
                }

                AppDefault appDefault = new AppDefault();
                String userid = appDefault.getUserid();
                String userkey = appDefault.getUserkey();
                if (silenceResult.silenceid == null) {
                    //添加静默设置
                    SaveSilenceParams saveSilenceParams = new SaveSilenceParams(userkey, userid, terminal.terminalid,
                            silenceResult.begintime, silenceResult.endtime, silenceResult.isopen, silenceResult.week);
                    send(saveSilenceParams);
                } else {
                    //修改静默设置
                    UpdateSilenceParams updateSilenceParams = new UpdateSilenceParams(userkey, userid, terminal.terminalid, silenceResult.begintime,
                            silenceResult.endtime, silenceResult.isopen, silenceResult.week, silenceResult.silenceid);
                    send(updateSilenceParams);
                }

                break;
            case R.id.title_bar_left_iv:
                finish();
                break;
        }
    }

    public void send(BasicParams params) {
        showProgress();
        networkModel.loadDataFromServer(new SocketRequest<BasicResult>(params, new NetworkListener<BasicResult>() {
            @Override
            public void onError(VolleyError error) {
                hideProgress();
                PromptUtil.toast(getApplicationContext(), R.string.app_no_connection);
            }

            @Override
            public void onSuccess(BasicResult response) {
                hideProgress();
                if (response.code == 0) {
                    setResult(99);
                    finish();
                }
            }
        }));
    }


    private void setAllWeekState() {
        checkbox_allweek.setOnCheckedChangeListener(null);
        if (silenceResult.week == 127) {
            checkbox_allweek.setChecked(true);
        } else {
            checkbox_allweek.setChecked(false);
        }
        checkbox_allweek.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.checkbox_allweek:
                checkbox_monday.setChecked(isChecked);
                checkbox_tuesday.setChecked(isChecked);
                checkbox_wednesday.setChecked(isChecked);
                checkbox_thursday.setChecked(isChecked);
                checkbox_firday.setChecked(isChecked);
                checkbox_saturday.setChecked(isChecked);
                checkbox_sunday.setChecked(isChecked);
                break;
            case R.id.checkbox_monday:
                if (!isChecked) {
                    silenceResult.week -= 2;
                } else {
                    silenceResult.week += 2;
                }
                setAllWeekState();
                break;
            case R.id.checkbox_tuesday:
                if (!isChecked) {
                    silenceResult.week -= 4;
                } else {
                    silenceResult.week += 4;
                }
                setAllWeekState();
                break;
            case R.id.checkbox_wednesday:
                if (!isChecked) {
                    silenceResult.week -= 8;
                } else {
                    silenceResult.week += 8;
                }
                setAllWeekState();
                break;
            case R.id.checkbox_thursday:
                if (!isChecked) {
                    silenceResult.week -= 16;
                } else {
                    silenceResult.week += 16;
                }
                setAllWeekState();
                break;
            case R.id.checkbox_firday:
                if (!isChecked) {
                    silenceResult.week -= 32;
                } else {
                    silenceResult.week += 32;
                }
                setAllWeekState();
                break;
            case R.id.checkbox_saturday:
                if (!isChecked) {
                    silenceResult.week -= 64;
                } else {
                    silenceResult.week += 64;
                }
                setAllWeekState();
                break;
            case R.id.checkbox_sunday:
                if (!isChecked) {
                    silenceResult.week -= 1;
                } else {
                    silenceResult.week += 1;
                }
                setAllWeekState();
                break;

            default:
                break;
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
        networkModel.onStop();
    }
}
